package com.tuhao.www.filter;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;

/**
 * 全局的过滤器
 * 过滤请求地址的
 * 
 */
public class GlobalFilter implements Filter {

	private static final Logger LOGGER = Logger.getLogger(GlobalFilter.class);

	@Override
	public void destroy() {

	}

	@Override
	public void init(FilterConfig arg0) throws ServletException {

	}

	public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException,
		ServletException {
		HttpServletRequest request = (HttpServletRequest) req;
		String url = request.getRequestURI();
		Pattern p = Pattern.compile(".(jsp|jspx|php|asp|aspx)");
		Matcher m = p.matcher(url);
		boolean rs = m.find();
		List<String> pathList = notNeedCheck();
		if (pathList.contains(url)) {
			chain.doFilter(req, res);
		} else if (rs) {
			LOGGER.debug(".(jsp|jspx|php|asp|aspx) forbidden allow!");
			request.getRequestDispatcher("/404.htm").forward(req, res);
		} else {
			chain.doFilter(req, res);
		}
	}
	
	private List<String> notNeedCheck() {
        String[] paths = new String[] {"/imageUp.jsp", "/upfile.jsp", "/plugins/ueditor/jsp/controller.jsp", "/tick.jsp", "/busy.jsp"};
        return Arrays.asList(paths);
    }

}
